import os, amara

from wsgiappclient.namespaces import *
from wsgiappclient.atompubclient import AtomPubClient

class User(object):

    def __init__(self, user_id, store_dir='users', file_extension='xml'):
        self.prefixes = COMMON_PREFIXES
        self.prefixes[u'user'] = USER_NS
        self.store_dir = store_dir
        if not os.path.isdir(self.store_dir):
            os.makedirs(self.store_dir)
        self.file_extension = file_extension
        self.user_id = user_id
        self.user_file = '%s.%s' % (self.user_id, self.file_extension)
        self.user_file_path = os.path.join(self.store_dir, self.user_file)
        if os.path.exists(self.user_file_path):
            self.doc = amara.parse(self.user_file_path, prefixes=self.prefixes)
        else:
            self.doc = amara.create_document(u'user', USER_NS, prefixes=COMMON_PREFIXES)
            self.doc.user.xml_append(
                self.doc.xml_create_element(u'openid', content=unicode(self.user_id)))
            self.add_author({'atom_author_name' : user_id})
            self.save()

    def get(self):
        return self.doc

    def get_author(self):
        author = self.doc.xml_xpath('//atom:author')
        if author:
            return author[0].xml()
        else:
            return "<author><name>%s</name></author>" % self.user_id

    def add_author(self, data):
        if not self.doc.xml_xpath('//atom:author'):
            author = self.doc.xml_create_element(
                u'author', ATOM10_NS, content=unicode(self.user_id))
            author.xml_append(self.doc.xml_create_element(u'name', ATOM10_NS))
            author.xml_append(self.doc.xml_create_element(u'email', ATOM10_NS))
            author.xml_append(self.doc.xml_create_element(u'uri', ATOM10_NS))
            self.doc.user.xml_append(author)
            
        if data.get('atom_author_name'):
            if hasattr(self.doc.user.author, 'name'):
                name = self.doc.user.author.name
                self.doc.user.author.xml_remove_child(name)
            self.doc.user.author.xml_append(
                self.doc.user.author.xml_create_element(
                    u'name', ATOM10_NS, content=unicode(data['atom_author_name'])))

        if data.get('atom_author_email'):
            if hasattr(self.doc.user.author, 'email'):
                email = self.doc.user.author.email
                self.doc.user.author.xml_remove_child(email)
            self.doc.user.author.xml_append(
                self.doc.user.author.xml_create_element(
                    u'email', ATOM10_NS, content=unicode(data['atom_author_email'])))

        if data.get('atom_author_uri'):
            if hasattr(self.doc.user.author, 'uri'):
                uri = self.doc.user.author.uri
                self.doc.user.author.xml_remove_child(uri)
            self.doc.user.author.xml_append(
                self.doc.user.author.xml_create_element(
                    u'uri', ATOM10_NS, content=unicode(data['atom_author_uri'])))

        self.save()
        
    def get_xml(self):
        return self.doc.xml()

    def get_xml_with_collections(self):
        collections = self._get_collections()
        if not collections:
            return self.get_xml()
        tempdoc = amara.parse(self.doc.xml())
        for c in collections:
            tempdoc.user.xml_append(c.feed)
        return tempdoc.xml()

    def _get_collections(self):
        clist = []
        if not hasattr(self.doc.user, 'collection'):
            return 
        for collection in self.doc.user.collection:
            client = self.get_client(str(collection.href))
            c = client.get_collection(str(collection.href))
            print c
            print "Value of %s" % str(collection.href)
            clist.append(amara.parse(c, prefixes=COMMON_PREFIXES))
        return clist

    def get_collections(self):
        collections = self._get_collections()
        return [ c.xml() for c in collections ]
        
    def get_client(self, url):
        collection = self.get_collection(url)
        if hasattr(collection, 'username') and hasattr(collection, 'password'):
            client = AtomPubClient(username=collection.username, password=collection.password)
        else:
            client = AtomPubClient()
        return client

    def get_collection_by_id(self, cid):
        try:
            return self.doc.user.collection[int(cid) - 1]
        except Exception, e:
            print e
        return None

    def get_collection(self, url):
        if hasattr(self.doc.user, 'collection'):
            for c in self.doc.user.collection:
                if str(c.href) == url:
                    return c
        return None

    def add_collection(self, url, username=None, password=None):
        if not self.get_collection(url):
            attrs = { u'href' : unicode(url) }
            if username:
                attrs[u'username'] = unicode(username)
            if password:
                attrs[u'password'] = unicode(password)
            collection = self.doc.xml_create_element(
                u'collection', USER_NS,
                attributes=attrs
            )
            self.doc.user.xml_append(collection)
            self.save()

    def delete_collection(self, url):
        for i in range(0, len(self.doc.user.collection)):
            cur_href = str(self.doc.user.collection[i].href)
            if cur_href == url:
                cur_collection = self.doc.user.collection[i]
                self.doc.user.xml_remove_child(cur_collection)
                break
        self.save()

    def save(self):
        f = open(self.user_file_path, 'w+')
        self.doc.xml(f, indent=True)
        f.close()
